<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Admin\BaseController;
use App\Repositories\UserRepositoryEloquent;
use App\User;
use App\Models\Recharge;
use Breadcrumbs, Toastr,Config,Validator,DB;
use Illuminate\Http\Request;
use App\Models\Withdrawals;

class WithdrawalsController extends BaseController{

    public function __construct(UserRepositoryEloquent $user)
    {
        parent::__construct();
        $this->user = $user;
    }

    public function index(Request $request){
        $where=[];
        $whereHas=[];
        $data=['status'=>-1,'name'=>'','type'=>'','mobile'=>'','from'=>'','to'=>''];

        if(!empty($request->all())){
            //if($request->name){
            //dd($request->all());
            $datas = $request->all();
            foreach($datas as $k=>$v){
                if(($k=='name' || $k=='mobile') && $v!=''){
                    $whereHas[] = ["$k",'like','%'.$v.'%'];
                }
                if($k=='from' && $v!=''){
                    //$where[] = ['created_at','>',strtotime($v)];
                    $where[] = ['created_at','>',$v];
                }
                if($k=='to' && $v!=''){
                    //$where[] = ["created_at",'<',strtotime($v)];
                    $where[] = ["created_at",'<',$v];
                }
                if($k=='status' && $v!='' && $v!=-1){
                    $where[] = ["$k",'=',$v];
                }
                $data[$k] =$v;
                
            }
            //dd($where);
            //$users = User::where($where)->paginate(20);
        }

        $withdrawals = Withdrawals::where($where)
                        ->whereHas('user',function($query) use($whereHas){
                            $query->where($whereHas);
                        })->orderBy('id','desc')->paginate(20);
        return view('admin.finance.withdrawals',compact('withdrawals','data'));
    }

    /**
     * [transfer 转账]
     * @return [type] [description]
     */
    public function transfer($id){
        $withdrawals = Withdrawals::where('id','=',$id)->where('status','=',0)->first();
        if(!$withdrawals){ 
            return response()->json(['status' => -1,'msg'=>'没有相关提现记录！']);
        }
        if($withdrawals->user->frozen_funds<($withdrawals->money+$withdrawals->fee)){
            return response()->json(['status' => -1,'msg'=>'冻结资金异常！']);
        }
        
        DB::beginTransaction();
        try{
            $result = null;
            $res = Withdrawals::where('id','=',$id)->where('status','=',0)->update(['type'=>1,'status'=>1]);
            if($res){
                $user = User::find($withdrawals->user->id);
                $user->frozen_funds = $user->frozen_funds-($withdrawals->money+$withdrawals->fee);
                $result = $user->save();
            }
            DB::commit(); 
            return response()->json($result ? ['status' => 1] : ['status' => -1,'msg'=>'扣除冻结资金失败']);
        }catch(\Exception $e){
            //接收异常处理并回滚 
            DB::rollBack(); 
            return response()->json(['status' => -1,'msg'=>'处理数据异常！']);
        }
       
    }

    /**
     * [enterprise 企业付款]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function enterprise($id){
       
        $withdrawals = Withdrawals::where('id','=',$id)->where('status','=',0)->first();
       
        if(!$withdrawals){ 
            return response()->json(['status' => -1,'msg'=>'没有相关提现记录！']);
        }
        if($withdrawals->user->frozen_funds<($withdrawals->money+$withdrawals->fee)){
            return response()->json(['status' => -1,'msg'=>'冻结资金异常！']);
        }
         $user = User::find($withdrawals->user->id);
        DB::beginTransaction();
        try{

            $wechat = app('wechat');
            $merchantPay = $wechat->merchant_pay;
            $merchantPayData = [
                'partner_trade_no' => $withdrawals->partner_trade_no, //随机字符串作为订单号，跟红包和支付一个概念。
                'openid' => $user->openid, //收款人的openid
                'check_name' => 'FORCE_CHECK',  //文档中有三种校验实名的方法 NO_CHECK OPTION_CHECK FORCE_CHECK
                're_user_name'=>$withdrawals->real_name,     //OPTION_CHECK FORCE_CHECK 校验实名的时候必须提交
                'amount' => $withdrawals->money*100,  //单位为分
                'desc' => '企业付款',
                'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],  //发起交易的IP地址
            ];
            $result = $merchantPay->send($merchantPayData);
            Withdrawals::where('id','=',$id)->update(['note'=>$result->return_msg]);
            if(!($result->return_code =='SUCCESS' && $result->result_code == 'SUCCESS')){
                return response()->json(['status' => -1,'msg'=>$result->return_msg]);
            }

            
            $res = Withdrawals::where('id','=',$id)
                                ->where('partner_trade_no','=',$result->partner_trade_no)
                                ->where('status','=',0)
                                ->update(['type'=>1,'status'=>1,'payment_no'=>$result->payment_no,'payment_time'=>$result->payment_time,'note'=>'企业付款成功！']);
            $result = null;
            if($res){
                $user->frozen_funds = $user->frozen_funds-($withdrawals->money+$withdrawals->fee);
                $result = $user->save();
            }
            DB::commit(); 
            return response()->json($result ? ['status' => 1] : ['status' => -1,'msg'=>'扣除冻结资金失败']);
        }catch(\Exception $e){
            //接收异常处理并回滚 
            DB::rollBack(); 
            return response()->json(['status' => -1,'msg'=>'处理数据异常！']);
        }

    }

    /**
     * [back 提现退回]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function back($id){
        $withdrawals = Withdrawals::where('id','=',$id)->where('status','=',0)->first();
        if(!$withdrawals){ 
            return response()->json(['status' => -1,'msg'=>'没有相关提现记录！']);
        }
        if($withdrawals->user->frozen_funds<($withdrawals->money+$withdrawals->fee)){
            return response()->json(['status' => -1,'msg'=>'冻结资金异常！']);
        }
        
        DB::beginTransaction();
        try{
            $result = null;
            $res = Withdrawals::where('id','=',$id)->where('status','=',0)->update(['status'=>2]);
            if($res){

                $user = User::find($withdrawals->user->id);
                $backMoney = $withdrawals->money+$withdrawals->fee;
                $note = "提现退回";
                $result = $result = $this->user->modifyBalance($user->id,$backMoney,5,$note,-$backMoney);
            }
            DB::commit(); 
            return response()->json($result ? ['status' => 1] : ['status' => -1,'msg'=>'扣除冻结资金失败']);
        }catch(\Exception $e){
            //接收异常处理并回滚 
            DB::rollBack(); 
            return response()->json(['status' => -1,'msg'=>'处理数据异常！']);
        }
    } 

}